var req;
var completeField;

function doCompletion(obj) {
    completeField = obj;
    var url = "autocomplete?action=complete&id=" + encodeURI(obj.value) + "&attribute=" + encodeURI(obj.name);
    req = initRequest();
    req.open("GET", url, true);
    req.onreadystatechange = callback;
    req.send(null);
}

function initRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

function callback() {
    clearInput();
    if (req.readyState == 4) {
        if (req.status == 200) {
            parseMessages(req.responseXML);
        }
    }
}

function appendObject(name) {
    var li = "<li>"+name+"</li>";
    $(completeField).next().append(li);
    selectElement();
}

function clearInput() {
    $(completeField).next().empty();
}

function parseMessages(responseXML) {
    if (responseXML==null) {
        return false;
    } else {
        var objects = responseXML.getElementsByTagName("objects")[0];
        if (objects.childNodes.length>0) {
            for(var loop=0; loop<objects.childNodes.length; loop++) {
                var object = objects.childNodes[loop];
                var name = object.getElementsByTagName("name")[0].childNodes[0];
                appendObject(name.nodeValue);
            }
        }
    }
}

function selectElement () {
    $('.ul_select li').click( function() {
        var tx = $(this).html();
        $("ul.select").slideUp('fast');
        $("#complete-field").val(tx);
        clearInput();
    })
}